package com.snails.app.utils;

import android.content.Context;

import androidx.annotation.Nullable;

import com.snails.app.SnailsApp;
import com.snails.net.utils.DiskLruCacheHelper;

import java.io.IOException;

/**
 * @author lawrence
 * @date 2019-04-29 15:33
 */
public final class DiskLruCacheUtil {
    // ----------------------------------------------------------------------------
    // -----------  ------------
    // ----------------------------------------------------------------------------
    private static int appVersion = 1;
    public static void setVersion(int version) {
        DiskLruCacheUtil.appVersion = version;
    }

    private static final class Holder {
        private static final DiskLruCacheUtil INSTANCE = new DiskLruCacheUtil();
    }

    @Nullable
    public static DiskLruCacheHelper getDiskLruCacheHelper() {
        return Holder.INSTANCE.mDiskLruCache;
    }

    // ----------------------------------------------------------------------------
    // -----------  ------------
    // ----------------------------------------------------------------------------
    private final Context mCtx;
    private static DiskLruCacheHelper mDiskLruCache = null;

    private DiskLruCacheUtil() {
        checkCtx(this.mCtx = SnailsApp.instance().getCtx());
        try {
            this.mDiskLruCache = new DiskLruCacheHelper.Builder()
                    .appVersion(DiskLruCacheUtil.appVersion)
                    .maxSize(15 * 1024 * 1024) // 15MB
                    .build(this.mCtx, "diskLruCache");
        } catch (IOException e) {
            e.printStackTrace();
            this.mDiskLruCache = null;
        }
    }

    // 检测Context是否已初始化
    private void checkCtx(Context ctx) {
        if (ctx == null) {
            throw new NullPointerException("请先调用【SnailsApp.instance().init()】进行初始化。");
        }
    }

}
